package com.aoip.telemetry.telemetry.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * @author chenbai
 * @version 1.0
 * @Description TODO
 * @date 2022/2/23 21:11
 */
public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {


    public static void main(String[] args) {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .handler(new UdpClientHandler());

            Channel ch = b.bind(0).sync().channel();

            ch.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer("ST 6071860J43 TT 06012115 PN05 0 RC 2930 Z01 27549 Z02 2 BV 130 SI1 31 DC 0 ggNN", CharsetUtil.UTF_8),
                    new InetSocketAddress("127.0.0.1", 21001))).sync();

            ch.closeFuture().await();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        String body = packet.content().toString(CharsetUtil.UTF_8);
        System.out.println(body);
    }

//    if (StringUtils.hasText(counter)) {
//        if ("9999".equals(counter)) {
//            num = 0;
//        } else {
//            num = Integer.valueOf(counter) + 1;
//        }
//    } else {
//        num = 0;
//    }
}
